package mspbots.data.sync.rippling.receivers;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.data.sync.BaseReceiver;
import mspbots.data.sync.ResultMessageModel;
import mspbots.data.sync.rippling.model.RipplingCompanies;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Optional;

/**
 * @author Jay Yang
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class RipplingCompaniesReceiver extends BaseReceiver {

    @RabbitListener(queues = "rippling.companies.sync")
    public void processCompanies(ResultMessageModel model) {
        log.debug("processCompanies[rippling.companies.sync] ResultMessageModel {}", model);
        if (ResultMessageModel.MessageModelAction.ADD.equals(model.getAction())) {
            JsonNode companiesNode = model.getEntity();
            RipplingCompanies companies = this.objectMapper.convertValue(companiesNode, RipplingCompanies.class);
            companies.setExtend(companiesNode);
            companies.setTenantId(model.getTenantId());
            companies.setSyncTime(model.getSendTime());

            Optional<Long> id = this.databaseClient.execute("select id from rippling_companies " +
                    "where tenant_id =:tenantId and other_id =:otherId")
                    .as(Long.class)
                    .bind("tenantId", companies.getTenantId())
                    .bind("otherId", companies.getOtherId())
                    .fetch().one().blockOptional(Duration.ofSeconds(10));

            if (id.isPresent() && id.get() > 0) {
                companies.setId(id.get());
                this.databaseClient.update().table(RipplingCompanies.class).using(companies).fetch().rowsUpdated().subscribe();
            } else {
                this.databaseClient.insert().into(RipplingCompanies.class).using(companies).fetch().rowsUpdated().subscribe();
            }

        }
    }
}
